package com.sciyichen.tcpclientbytes;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Base64;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;

public class TcpClientBytesPlugin extends UniModule {


    private static final String TAG = "TcpClientBytesPlugin";
    private static final Logger logger = Logger.getLogger(TAG);

    private final ExecutorService executorService = Executors.newCachedThreadPool();
    private final TcpClientBytesPluginImpl packetOperations;

    private UniJSCallback stringCallback;
    private UniJSCallback dataByteArrayCallback;
    private UniJSCallback dataByteArrayBase64StrCallback;
    private UniJSCallback dataByteArrayHexCallback;

    private boolean isInitialized = false;

    public TcpClientBytesPlugin() {
        packetOperations = new TcpClientBytesPluginImpl();
    }
    private void submitToExecutor(Runnable runnable, UniJSCallback successCallback, UniJSCallback errorCallback) {
        executorService.submit(() -> {
            try {
                runnable.run();
            } catch (Exception e) {
                String errorMsg = "操作异常: " + e.getMessage();
                logger.log(Level.SEVERE, errorMsg, e);
//               packetOperations.stopDataReceiver();
                if (errorCallback != null) {
                    errorCallback.invoke(errorMsg);
                }
            }
        });
    }
    @UniJSMethod(uiThread = true)
    public void destroy() {
        try {
            logger.info("销毁插件");

            // 关闭连接
            if (isConnected()) {
                packetOperations.close(
                        result -> logger.info("连接关闭成功"),
                        error -> logger.severe("连接关闭失败: " + error)
                );
            }

            // 清除回调
            clearCallbacks();

            // 关闭线程池
            if (!executorService.isShutdown()) {
                executorService.shutdown();
            }

            // 重置初始化状态
            isInitialized = false;
        } catch (Exception e) {
            LogUtils.e(TAG, "销毁插件异常", e);
        }
    }
    private boolean checkPermission() {
        Context uniAppContext = this.mWXSDKInstance.getContext();
        if (uniAppContext == null) {
            return false;
        }

        return ContextCompat.checkSelfPermission(uniAppContext, Manifest.permission.INTERNET)
                == PackageManager.PERMISSION_GRANTED;
    }

    @UniJSMethod(uiThread = true)
    public void checkJdkVersion() {
        String version = System.getProperty("java.version");
        assert version != null;
        if (version.startsWith("1.8")) {
            throw new RuntimeException("当前使用JDK 8，版本兼容");
        } else if (version.startsWith("11")) {
            throw new RuntimeException("当前使用JDK 11，版本兼容");
        } else {
            throw new RuntimeException("未知JDK版本: " + version);
        }
    }

    @UniJSMethod(uiThread = true)
    public void getJavaVersion(UniJSCallback callback) {
        String version = System.getProperty("java.version");
        String vendor = System.getProperty("java.vendor");
        String runtime = System.getProperty("java.runtime.version");

        JSONObject info = new JSONObject();
        info.put("version", version);
        info.put("vendor", vendor);
        info.put("runtime", runtime);

        if (callback != null) {
            callback.invoke(info);
        }
    }

    @UniJSMethod(uiThread = true)
    public void initialize(UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isInitialized) {

                isInitialized = true;
            }
            if (successCallback != null) {
                successCallback.invoke("初始化成功");
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "初始化失败", e);
            if (errorCallback != null) {
                errorCallback.invoke("初始化失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void connect(String host, int port, int timeout, UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!checkPermission()) {
                if (errorCallback != null) {
                    errorCallback.invoke("缺少网络权限，请在 manifest 中声明 INTERNET 权限");
                }
                return;
            }

            if (!isInitialized) {
                if (errorCallback != null) {
                    errorCallback.invoke("请先调用initialize方法");
                }
                return;
            }

            if (isConnected()) {
                if (successCallback != null) {
                    successCallback.invoke("已连接");
                }
                return;
            }

            logger.info("尝试连接到: " + host + ":" + port);

            submitToExecutor(() -> {
                try {
                    logger.info("开始创建 Socket 连接...");
                    packetOperations.connect(host, port, timeout,
                            result -> {

                                logger.info("连接成功: " + result);
                                if (successCallback != null) {
                                    successCallback.invoke(result);
                                }
                                startDataReceiver();
                            },
                            error -> {

                                logger.severe("连接失败: " + error);
                                if (errorCallback != null) {
                                    errorCallback.invoke(error);
                                }
                            }
                    );
                } catch (Exception e) {
                    String errorMsg = "连接异常: " + e.getMessage();
                    logger.log(Level.SEVERE, errorMsg, e);

                    if (errorCallback != null) {
                        errorCallback.invoke(errorMsg);
                    }
                }
            }, successCallback, errorCallback);
        } catch (Exception e) {
            String errorMsg = "连接失败: " + e.getMessage();
            logger.log(Level.SEVERE, errorMsg, e);
            if (errorCallback != null) {
                errorCallback.invoke(errorMsg);
            }
        }
    }
    private void dataCallback(byte[] data){
        // 处理不同格式的回调
        if (dataByteArrayCallback != null) {
            dataByteArrayCallback.invoke(data);
        }

        if (dataByteArrayBase64StrCallback != null) {
            String base64Str = Base64.encodeToString(data, Base64.DEFAULT);
            dataByteArrayBase64StrCallback.invoke(base64Str);
        }

        if (dataByteArrayHexCallback != null) {
            String hex = packetOperations.bytesToHex(data);
            dataByteArrayHexCallback.invoke(hex);
        }

        if (stringCallback != null) {
            try {
                String strData = new String(data, StandardCharsets.UTF_8);
                stringCallback.invoke(strData);
            } catch (Exception e) {
                logger.log(Level.WARNING, "转换为字符串失败", e);
            }
        }
    }
    // TcpClientBytesPluginImpl 中的回调接口
    public interface OnDataReceivedCallback {
        void onDataReceived(byte[] data);
    }
    // TcpClientBytesPlugin.java
    private void startDataReceiver() {
        Context uniAppContext = this.mWXSDKInstance.getContext();
        if (uniAppContext == null) {
            logger.log(Level.SEVERE, "uniAppContext 为 null，无法执行 UI 线程回调");
            return;
        }

        // 停止之前的接收线程（如果有）
        packetOperations.stopDataReceiver();

        // 设置数据回调
        packetOperations.setDataByteArrayCallback(data -> {
            if (uniAppContext instanceof Activity) {
                Activity activity = (Activity) uniAppContext;
                try {
                    activity.runOnUiThread(() -> {
                        // 处理不同格式的回调
                        dataCallback(data);

                    });
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "执行 UI 线程回调异常", e);
                }
            } else {
                logger.log(Level.SEVERE, "无法获取 Activity，无法执行 UI 线程回调");
            }
        });

        // 启动数据接收（调用实现类的方法，但不在实现类中启动新线程）
        executorService.submit(() -> {
            try {
                logger.info("启动数据接收线程，持续监听Socket数据...");
                packetOperations.startContinuousDataReceiving();
            } catch (Exception e) {
                logger.log(Level.SEVERE, "数据接收线程异常", e);
                // 通知UI线程
                if (uniAppContext instanceof Activity) {
                    Activity activity = (Activity) uniAppContext;
                    activity.runOnUiThread(() -> {
                        dataCallback(new byte[0]);
                    });
                }
            }
        });
    }
    // 在 TcpClientBytesPlugin 中
    public boolean isConnected() {
        return packetOperations.isConnected();
    }
    @UniJSMethod(uiThread = true)
    public void requestPermission(@NonNull UniJSCallback callback) {
        Context uniAppContext = this.mWXSDKInstance.getContext();
        if (uniAppContext == null) {
            callback.invoke("无法获取上下文，无法请求权限");
            return;
        }


        if (uniAppContext  instanceof Activity) {
            Activity activity = (Activity) uniAppContext;
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.INTERNET}, 1001);
            callback.invoke("已发起权限请求，请确认");
        } else {
            callback.invoke("无法获取 Activity，无法请求权限");
        }
    }

    @UniJSMethod(uiThread = false)
    public void sendBytes(byte[] data, UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isConnected()) {
                if (errorCallback != null) {
                    errorCallback.invoke("未连接");
                }
                return;
            }

            logger.info("发送字节数据，长度: " + data.length);


            submitToExecutor(() -> {
                packetOperations.sendBytes(data,
                        result -> {
                            if (successCallback != null) {
                                successCallback.invoke(result);
                            }
                        },
                        error -> {
                            if (errorCallback != null) {
                                errorCallback.invoke(error);
                            }
                        }
                );
            }, successCallback, errorCallback);
        } catch (Exception e) {
            logger.log(Level.SEVERE, "发送字节数据失败", e);

            if (errorCallback != null) {
                errorCallback.invoke("发送字节数据失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void sendBase64Str(String base64Str, UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isConnected()) {
                if (errorCallback != null) {
                    errorCallback.invoke("未连接");
                }
                return;
            }

            logger.info("发送Base64字符串数据，长度: " + base64Str.length());

            executorService.submit(() -> {
                try {
                    packetOperations.sendBase64Str(base64Str,
                            result -> {
                                if (successCallback != null) {
                                    successCallback.invoke(result);
                                }
                            },
                            error -> {

                                if (errorCallback != null) {
                                    errorCallback.invoke(error);
                                }
                            }
                    );
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "发送Base64字符串数据异常", e);

                    if (errorCallback != null) {
                        errorCallback.invoke("发送Base64字符串数据异常: " + e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            logger.log(Level.SEVERE, "发送Base64字符串数据失败", e);

            if (errorCallback != null) {
                errorCallback.invoke("发送Base64字符串数据失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void sendHex(String hexStr, UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isConnected()) {
                if (errorCallback != null) {
                    errorCallback.invoke("未连接");
                }
                return;
            }

            logger.info("发送Hex字符串数据，长度: " +hexStr.length());

            executorService.submit(() -> {
                try {
                    byte [] bytes=packetOperations.hexToBytes(hexStr);
                    packetOperations.sendBytes(bytes,
                            result -> {
                                if (successCallback != null) {
                                    successCallback.invoke(result);
                                }
                            },
                            error -> {

                                if (errorCallback != null) {
                                    errorCallback.invoke(error);
                                }
                            }
                    );
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "发送hexStr字符串数据异常", e);

                    if (errorCallback != null) {
                        errorCallback.invoke("发送hexStr字符串数据异常: " + e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            logger.log(Level.SEVERE, "发送hexStr字符串数据失败", e);

            if (errorCallback != null) {
                errorCallback.invoke("发送Base64字符串数据失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void send(String data, UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isConnected()) {
                if (errorCallback != null) {
                    errorCallback.invoke("未连接");
                }
                return;
            }

            logger.info("发送字符串数据，长度: " + data.length());

            executorService.submit(() -> {
                try {
                    packetOperations.send(data,
                            result -> {
                                if (successCallback != null) {
                                    successCallback.invoke(result);
                                }
                            },
                            error -> {

                                if (errorCallback != null) {
                                    errorCallback.invoke(error);
                                }
                            }
                    );
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "发送字符串数据异常", e);
//                    isConnected.set(false);
                    if (errorCallback != null) {
                        errorCallback.invoke("发送字符串数据异常: " + e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            logger.log(Level.SEVERE, "发送字符串数据失败", e);
//            isConnected.set(false);
            if (errorCallback != null) {
                errorCallback.invoke("发送字符串数据失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void close(UniJSCallback successCallback, UniJSCallback errorCallback) {
        try {
            if (!isConnected()) {
                if (successCallback != null) {
                    successCallback.invoke("已关闭");
                }
                return;
            }

            logger.info("关闭连接");

            executorService.submit(() -> {
                try {
                    packetOperations.close(
                            result -> {
//                                isConnected.set(false);
                                if (successCallback != null) {
                                    successCallback.invoke(result);
                                }
                            },
                            error -> {
//                                isConnected.set(false);
                                if (errorCallback != null) {
                                    errorCallback.invoke(error);
                                }
                            }
                    );
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "关闭连接异常", e);
//                    isConnected.set(false);
                    if (errorCallback != null) {
                        errorCallback.invoke("关闭连接异常: " + e.getMessage());
                    }
                }
            });
        } catch (Exception e) {
            logger.log(Level.SEVERE, "关闭连接失败", e);
//            isConnected.set(false);
            if (errorCallback != null) {
                errorCallback.invoke("关闭连接失败: " + e.getMessage());
            }
        }
    }

    @UniJSMethod(uiThread = true)
    public void setStringCallback(UniJSCallback callback) {
        logger.info("设置字符串回调");
        this.stringCallback = callback;
    }

    @UniJSMethod(uiThread = true)
    public void setDataByteArrayCallback(UniJSCallback callback) {
        logger.info("设置字节数组回调");
        this.dataByteArrayCallback = callback;
    }

    @UniJSMethod(uiThread = true)
    public void setDataByteArrayBase64StrCallback(UniJSCallback callback) {
        logger.info("设置Base64字符串回调");
        this.dataByteArrayBase64StrCallback = callback;
    }
    @UniJSMethod(uiThread = true)
    public void setDataByteArrayHexCallback(UniJSCallback callback) {
        logger.info("设置Base64字符串回调");
        this.dataByteArrayHexCallback = callback;
    }
    @UniJSMethod(uiThread = true)
    public void clearCallbacks() {
        logger.info("清除所有回调");
        this.stringCallback = null;
        this.dataByteArrayCallback = null;
        this.dataByteArrayBase64StrCallback = null;
        this.dataByteArrayHexCallback=null;
    }

    @UniJSMethod(uiThread = true)
    public void crcCcitt(JSONObject params, UniJSCallback callback) {
        try {
            byte[] data = params.getString("data").getBytes();
            int crc = params.getIntValue("crc");
            int result = packetOperations.crcCcitt(data, crc);
            if (callback != null) {
                callback.invoke(result);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }

    @UniJSMethod(uiThread = true)
    public void buildPacketFromJson(JSONObject params, UniJSCallback callback) {
        try {
            String outstr = params.getString("outstr");
            int checksum = params.getIntValue("checksum");
            byte[] result = packetOperations.buildPacketFromJson(outstr, checksum);
            if (callback != null) {
                callback.invoke(new String(result, "UTF-8"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    @UniJSMethod(uiThread = true)
    public void bufferToJson(JSONObject params, UniJSCallback callback) {
        try {
            byte[] pBuffer = params.getString("pBuffer").getBytes();
            int nStart = params.getIntValue("nStart");
            int nOffset = params.getIntValue("nOffset");
            Object[] result = packetOperations.bufferToJson(pBuffer, nStart, nOffset);
            if (callback != null) {
                JSONArray jsonArray = new JSONArray();
                for (Object obj : result) {
                    jsonArray.add(obj);
                }
                callback.invoke(jsonArray.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }
    @UniJSMethod(uiThread = true)
    public void getDataFromBytesBase64(JSONObject params, UniJSCallback callback) {
        try {
            String bytesBase64Str = params.getString("bytesBase64Str");
            int buffSize = params.getIntValue("buffSize");
            List<String> result = packetOperations.getDataFromBytesBase64(bytesBase64Str, buffSize);
            if (callback != null) {
                JSONArray jsonArray = new JSONArray();
                for (String map : result) {
                    jsonArray.add(JSONObject.parseObject(map));
                }
                callback.invoke(jsonArray.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }
    @UniJSMethod(uiThread = true)
    public void getAJsonPacketFromSocket(JSONObject params, UniJSCallback callback) {
        try {
            byte[] nBytes = params.getString("nBytes").getBytes();
            int buffSize = params.getIntValue("buffSize");
            List<String> result = packetOperations.getAJsonPacketFromSocket(nBytes, buffSize);
            if (callback != null) {
                JSONArray jsonArray = new JSONArray();
                for (String map : result) {
                    jsonArray.add(JSONObject.parseObject(map));
                }
                callback.invoke(jsonArray.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }
    @UniJSMethod(uiThread = true)
    public void getAJsonPacketFromHex(JSONObject params, UniJSCallback callback) {
        try {
            String hex= params.getString("hex");
            byte[] nBytes = packetOperations.hexToBytes(hex);
            int buffSize = params.getIntValue("buffSize");
            List<String> result = packetOperations.getAJsonPacketFromSocket(nBytes, buffSize);
            if (callback != null) {
                JSONArray jsonArray = new JSONArray();
                for (String map : result) {
                    jsonArray.add(JSONObject.parseObject(map));
                }
                callback.invoke(jsonArray.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void TcpClientBytes(JSONObject params, UniJSCallback callback) {
        try {
            String ip = params.getString("ip");
            int port = params.getIntValue("port");
            int buffSize = params.getIntValue("buffSize");
            if (buffSize < 1) {
                buffSize = 1024;
            }
            int timeout;
            try {
                timeout = params.getIntValue("timeout");
            } catch (Exception e) {
                timeout = 0;
            }
            String base64String = params.getString("data");
//            TcpClientBytesPluginImpl packetOperations = new TcpClientBytesPluginImpl();
            byte[] byteArray2 = packetOperations.tcpClientBytes(ip, port, base64String, buffSize, timeout);
            String base64String2 = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                base64String2 = Base64.encodeToString(byteArray2, Base64.DEFAULT);
            }
            if (callback != null) {
                callback.invoke(base64String2);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void TcpClientJsonData(String jsonstr, UniJSCallback callback) {
        JSONObject params = JSONObject.parseObject(jsonstr);
        String ip = params.getString("ip");
        int port = params.getIntValue("port");
        int buffSize = params.getIntValue("buffSize");
        if (buffSize < 1) {
            buffSize = 1024;
        }
        String jsonStr = params.getString("data");

//        TcpClientBytesPluginImpl packetOperations = new TcpClientBytesPluginImpl();

        int checksum = packetOperations.crcCcitt(jsonStr.getBytes(), 0);
        byte[] byteArray = packetOperations.buildPacketFromJson(jsonstr, checksum);
        String base64String = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            base64String = Base64.encodeToString(byteArray, Base64.DEFAULT);
        }
        int timeout = 0;
        try {
            timeout = params.getIntValue("timeout");
        } catch (Exception e) {
            timeout = 0;
        }
        byte[] byteArray2 = packetOperations.tcpClientBytes(ip, port, base64String, buffSize, timeout);
        String base64String2 = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            base64String2 = Base64.encodeToString(byteArray2, Base64.DEFAULT);
        }
        if (callback != null) {
            callback.invoke(base64String2);
        }
    }

    @UniJSMethod(uiThread = false)
    public void TcpClientJsonStr(String jsonstr, UniJSCallback callback) {
        com.alibaba.fastjson.JSONObject params = com.alibaba.fastjson.JSONObject.parseObject(jsonstr);
        String ip = params.getString("ip");
        int port = params.getIntValue("port");
        int buffSize = params.getIntValue("buffSize");
        if (buffSize < 1) {
            buffSize = 1024;
        }
        String base64String = params.getString("data");
        int timeout;
        try {
            timeout = params.getIntValue("timeout");
        } catch (Exception e) {
            timeout = 0;
        }
//        TcpClientBytesPluginImpl packetOperations = new TcpClientBytesPluginImpl();
        byte[] byteArray2 = packetOperations.tcpClientBytes(ip, port, base64String, buffSize, timeout);
        String base64String2 = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            base64String2 = Base64.encodeToString(byteArray2, Base64.DEFAULT);
        }
        if (callback != null) {
            callback.invoke(base64String2);
        }
    }

    @UniJSMethod(uiThread = false)
    public void tcpClientByte(JSONObject params, UniJSCallback callback) {
        try {
            String host = params.getString("host");
            int port = params.getIntValue("port");
            String base64str = params.getString("base64str");
            int buffSize = params.getIntValue("buffSize");
            int timeout;
            try {
                timeout = params.getIntValue("timeout");
            } catch (Exception e) {
                timeout = 0;
            }
            List<String> result = packetOperations.tcpClientByte(host, port, base64str, buffSize, timeout);
            if (callback != null) {
                JSONArray jsonArray = new JSONArray();
                for (String map : result) {
                    try {
                        jsonArray.add(JSONObject.parseObject(map));
                    } catch (JSONException e) {
                        jsonArray.add(map);
                    }
                }
                callback.invoke(jsonArray.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            if (callback != null) {
                callback.invoke("参数错误");
            }
        }
    }

    @UniJSMethod(uiThread = false)
    public void str(String str, UniJSCallback callback) {
        if (callback != null) {
            callback.invoke(str);
        }
    }

    @UniJSMethod(uiThread = false)
    public void jsonobj(JSONObject jsonObject, UniJSCallback callback) {
        if (callback != null) {
            callback.invoke(jsonObject);
        }
    }

    @UniJSMethod(uiThread = false)
    public void testConnection(String host, int port, @NonNull UniJSCallback callback) {
        try {
            Socket testSocket = new Socket(host, port);
            callback.invoke("连接成功");
            testSocket.close();
        } catch (IOException e) {
            callback.invoke("连接失败: " + e.getMessage());
        }
    }
}